import asyncio, asyncpg
"""

    获取前5个产品 - 还可以通过aiostream操作

"""

async def take(generator, to_take):
    item_count = 0
    async for item in generator:
        if item_count > to_take - 1:
            return
        item_count += 1
        yield item


async def main():
    connection = await asyncpg.connect(
        host="127.0.0.1",
        port="5432",
        database="products",
        user="around",
        password="zhouwei",
    )

    async with connection.transaction():
        query = "select product_id, product_name from product"
        # 为查询创建游标
        product_generator = connection.cursor(query)

        async for product in take(product_generator, 5):
            print(product)

        print('获取前5个产品')

    await connection.close()


asyncio.run(main())
